#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import email
import time

from abstract import *
from parseemail import *
from synsheets import *

from django.core.management.base import NoArgsCommand
from pp_case.models import PPCaseInfo

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        readEmails()

def decode_subject(subject):
    #解码主题信息
    PPInfo = {'status':'',
              'reason':'',
              'paypalCaseWindow':1,
              'isPayPalUpdate':False,
              'paypalRefreshDate':None,
              }
    
    refund_word = [
        '要求',
        'Request',
        '升级',
        'Escalated',
    ]
    #要先搜索dispute_word中的词语，因为refund_word中是最新状态
    dispute_word = ["争议",
                    '新的',
                    '新消息',
                    'Dispute',
                    'dispute',
                    'New',
                    ]
    charge_back_word = ['收到的事件',
                        'Case received',
                        ]
    not_as_desc_word = ["与描述显著不符",
				"Described",
				]
    no_reciept_word = ["物品未收到",
                       "Received",
                       ]
    close_word = ["结束",
                  "解决",
                  "Completion",
                  "买家的信用卡公司撤销了对您收到的一笔付款收取的费用",
                  "Resolution ",
                  ]
    news_word = ["消息",
                 '升级',
                 ]
    unauthorised_word = ['调查付款撤销',
                         'We\'re investigating a payment reversal',
                         ]
    for i in no_reciept_word :
        if subject.find(i) != -1 :
            PPInfo['reason'] = '未收到'
            break
    for i in not_as_desc_word :
        if subject.find(i) != -1 :
            PPInfo['reason'] = '与描述不相符'
            break
    for i in unauthorised_word :
        if subject.find(i) != -1 :
            PPInfo['reason'] = '未经授权'
            break
    
    for i in dispute_word :
        if subject.find(i) != -1 :
            PPInfo['status'] = '争议'
            break
    for i in refund_word :
        if subject.find(i) != -1 :
            PPInfo['status'] = '补偿请求'
            break
    for i in charge_back_word:
        if subject.find(i) != -1:
            PPInfo['status'] = '退单'

    for i in news_word:
        if subject.find(i) != -1:
            PPInfo['isPayPalUpdate'] = True
            break
    for i in close_word :
        if subject.find(i) != -1:
            PPInfo['paypalCaseWindow'] = 2
            break

    return  PPInfo

def syncModel (trans):
    try:
        case = PPCaseInfo.objects.get(pk=trans['case_id'])
        # synchronize other data
        # maybe need to complete the case information
        if trans['reason']:
            case.paypalCaseDeclaration = trans['reason']
        if trans['status']:
            case.paypalCaseStatus = trans['status']
        if trans['paypalCaseWindow']:
            case.paypalCaseWindow = trans['paypalCaseWindow']
        # PayPal/Customer has update/refresh this case
        # Or the case has be closed , we need to know the result 
        if trans['isPayPalUpdate'] or trans['paypalCaseWindow'] == 2:
            case.isPayPalUpdate = True
            case.paypalRefreshDate = trans['date']
        case.save()
    except PPCaseInfo.DoesNotExist:
        # get the case on the first time
        case = PPCaseInfo.objects.create(
            pk=trans['case_id'],
            orderNo=trans['invoice_no'],
            paymentAmount=trans['amount'],
            paymentCurrency=trans['currency'],
            transactionID = trans['transaction_no'],
            caseStartDate = trans['date'],
            paypalCaseDeclaration = trans['reason'],
            paypalCaseStatus = trans['status'],
            paypalCaseWindow = trans['paypalCaseWindow'],
            isPayPalUpdate = trans['isPayPalUpdate'],
            processStatus = 0,
            paypalRefreshDate = None
        )
        case.save()
def readEmails():
    #config= ConfigParser.ConfigParser()
    #config.read(os.path.join('..','config','mail.cfg'))

    #some info needed when connecting server
    #hostname = config.get('server', 'hostname')
    #username = config.get('ppemailaccount', 'username')
    #password = config.get('ppemailaccount', 'password')
    hostname = 'imap.qiye.163.com'
    username = 'paypal@milanoo.com'
    password = 'hwzhz88'
    server_port = 993

    #connect to server
    m = imaplib.IMAP4_SSL(hostname,server_port)
    m.login(username, password)
    m.select('INBOX',readonly=True)
    typ,data = m.search(None,'UNSEEN')
    unreaduid = data[0].split()
    #unreaduid = range(39422,39457)
    # I will change the unreanduid for testing, end to uid

    for email_id in unreaduid:
        print 'get email %s ...' % email_id
        resp, data = m.fetch(email_id,'(RFC822)')
        #set email to Seen status
        body =  email.message_from_string(data[0][1])
        from_addr = body['From']
        raw_date    = body['Date']
        date = time.strftime("%y-%m-%d",email.utils.parsedate(raw_date))
        raw_subject = body['Subject']
        #translate the date format
        match1   = re.match(r".*service@intl.paypal.com",from_addr)
        re_case = re.compile(r'.*(PP-\d{3}-\d{3}-\d{3}-\d{3})')

        if match1:
            match2 = re_case.match(raw_subject)
            m.store(email_id,"+FLAGS","\\Seen")
            if match2:
                whole_body = get_mail_contents(body)
                for part in whole_body :
                    if part.is_body == 'text/plain':
                        payload, used_charset = decode_text(part.payload,part.charset,'auto')
                        break
                print "解码为:%s"%used_charset
                try:
                    subject_code = raw_subject.decode(used_charset).encode('utf8')
                except UnicodeError:
                    subject_code = raw_subject
                info = payload.encode('utf8')
                if used_charset == 'gb2312':
                    lang = 'ch'
                else:
                    lang = 'en'
                #编码处理结束
                #解码信件内容
                trans = abstract_tran_info(info,lang)
                if not trans['case_id']:
                    trans['case_id'] = match2.groups()[0]
                trans['date'] = date
                
                #解码主题
                temp = decode_subject(subject_code)
                trans['reason'] =temp['reason']
                trans['status'] =temp['status']
                trans['isPayPalUpdate']= temp['isPayPalUpdate']
                trans['paypalCaseWindow'] = temp['paypalCaseWindow']
                # synchronize the Data Model with trans dict
                print trans
                syncModel(trans)
                # continue synchronize with excel data
                #synsheets(trans)
